package com.helei.springcloud.controller;

import com.helei.springcloud.entity.Payment;
import com.helei.springcloud.entity.Resp;
import com.helei.springcloud.service.IPaymentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author helei
 * @description PaymentController
 * @date 2020/7/15 9:23
 */
@RestController
public class PaymentController {
    @Resource
    IPaymentService paymentService;
    @Value("${server.port}")
    private String sort;
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "provider/aa")
    public Resp create() {
        Payment payment = new Payment();
        payment.setSerial("cloud");
        paymentService.save(payment);
        return Resp.getNew().success("添加成功+port:" + sort);
    }

    @GetMapping(value = "provider/bbb")
    public Object find(Integer id) {
        Payment payment = paymentService.getById(id);
        payment.setPort(sort);
        return Resp.getNew().success(payment);
    }

    @GetMapping(value = "provider/sdsad")
    public Object aa() {
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            System.out.println("****elenment: " + element);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance:instances){
            System.out.println(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeout() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return sort;
    }
}
